import 'package:flutter/material.dart';
import 'package:logger/logger.dart';

import '../../models/user.dart';
import '../../services/user_service.dart';
import '../../core/app_config.dart';
import '../../core/database_helper.dart';

/// 用户表单界面
class UserFormScreen extends StatefulWidget {
  final User? user;

  const UserFormScreen({super.key, this.user});

  @override
  State<UserFormScreen> createState() => _UserFormScreenState();
}

class _UserFormScreenState extends State<UserFormScreen> {
  final _formKey = GlobalKey<FormState>();
  final UserService _userService = UserService();
  final Logger _logger = Logger();
  
  final _usernameController = TextEditingController();
  final _passwordController = TextEditingController();
  final _realNameController = TextEditingController();
  final _emailController = TextEditingController();
  final _phoneController = TextEditingController();
  final _departmentController = TextEditingController();
  final _positionController = TextEditingController();
  
  int _selectedRole = 1;
  bool _isLoading = false;
  bool _isEditMode = false;

  @override
  void initState() {
    super.initState();
    _isEditMode = widget.user != null;
    if (_isEditMode && widget.user != null) {
      _loadUserData(widget.user!);
    }
  }

  /// 加载用户数据
  void _loadUserData(User user) {
    _usernameController.text = user.username;
    _realNameController.text = user.realName ?? '';
    _emailController.text = user.email ?? '';
    _phoneController.text = user.phone ?? '';
    _departmentController.text = user.department ?? '';
    _positionController.text = user.position ?? '';
    _selectedRole = user.role;
  }

  @override
  void dispose() {
    _usernameController.dispose();
    _passwordController.dispose();
    _realNameController.dispose();
    _emailController.dispose();
    _phoneController.dispose();
    _departmentController.dispose();
    _positionController.dispose();
    super.dispose();
  }

  /// 保存用户
  Future<void> _saveUser() async {
    if (!_formKey.currentState!.validate()) {
      return;
    }

    _logger.d('💾 开始保存用户: ${_usernameController.text}');
    setState(() {
      _isLoading = true;
    });

    try {
      final now = DateTime.now();
      final user = User(
        id: widget.user?.id,
        username: _usernameController.text.trim(),
        passwordHash: _isEditMode && _passwordController.text.isEmpty
            ? widget.user!.passwordHash
            : DatabaseHelper.hashPassword(_passwordController.text),
        realName: _realNameController.text.trim(),
        email: _emailController.text.trim().isEmpty ? null : _emailController.text.trim(),
        phone: _phoneController.text.trim().isEmpty ? null : _phoneController.text.trim(),
        role: _selectedRole,
        department: _departmentController.text.trim().isEmpty ? null : _departmentController.text.trim(),
        position: _positionController.text.trim().isEmpty ? null : _positionController.text.trim(),
        isActive: widget.user?.isActive ?? true,
        lastLoginTime: widget.user?.lastLoginTime,
        createdAt: widget.user?.createdAt ?? now,
        updatedAt: now,
        isDeleted: false,
      );

      bool success;
      if (_isEditMode) {
        success = await _userService.updateUser(user);
        _logger.i('✅ 用户更新成功: ${user.username}');
      } else {
        success = await _userService.createUser(user);
        _logger.i('✅ 用户创建成功: ${user.username}');
      }

      if (success) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(_isEditMode ? '用户更新成功' : '用户创建成功')),
        );
        Navigator.of(context).pop();
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(_isEditMode ? '更新用户失败' : '创建用户失败')),
        );
      }
    } catch (e) {
      _logger.e('❌ 保存用户失败: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('保存用户失败: $e')),
      );
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(_isEditMode ? '编辑用户' : '添加用户'),
        actions: [
          if (_isLoading)
            const Padding(
              padding: EdgeInsets.all(16),
              child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white),
            ),
        ],
      ),
      body: Form(
        key: _formKey,
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 用户名
              TextFormField(
                controller: _usernameController,
                decoration: const InputDecoration(
                  labelText: '用户名 *',
                  hintText: '请输入用户名',
                  prefixIcon: Icon(Icons.person),
                ),
                enabled: !_isEditMode, // 编辑模式下用户名不可修改
                validator: User.validateUsername,
              ),
              const SizedBox(height: 16),

              // 密码
              TextFormField(
                controller: _passwordController,
                decoration: InputDecoration(
                  labelText: _isEditMode ? '密码 (留空则不修改)' : '密码 *',
                  hintText: '请输入密码',
                  prefixIcon: const Icon(Icons.lock),
                ),
                obscureText: true,
                validator: _isEditMode ? null : User.validatePassword,
              ),
              const SizedBox(height: 16),

              // 真实姓名
              TextFormField(
                controller: _realNameController,
                decoration: const InputDecoration(
                  labelText: '真实姓名 *',
                  hintText: '请输入真实姓名',
                  prefixIcon: Icon(Icons.badge),
                ),
                validator: User.validateRealName,
              ),
              const SizedBox(height: 16),

              // 邮箱
              TextFormField(
                controller: _emailController,
                decoration: const InputDecoration(
                  labelText: '邮箱',
                  hintText: '请输入邮箱地址',
                  prefixIcon: Icon(Icons.email),
                ),
                keyboardType: TextInputType.emailAddress,
                validator: User.validateEmail,
              ),
              const SizedBox(height: 16),

              // 手机号
              TextFormField(
                controller: _phoneController,
                decoration: const InputDecoration(
                  labelText: '手机号',
                  hintText: '请输入手机号',
                  prefixIcon: Icon(Icons.phone),
                ),
                keyboardType: TextInputType.phone,
                validator: User.validatePhone,
              ),
              const SizedBox(height: 16),

              // 角色选择
              DropdownButtonFormField<int>(
                value: _selectedRole,
                decoration: const InputDecoration(
                  labelText: '角色 *',
                  prefixIcon: Icon(Icons.security),
                ),
                items: const [
                  DropdownMenuItem(value: 1, child: Text('普通用户')),
                  DropdownMenuItem(value: 2, child: Text('管理员')),
                ],
                onChanged: (value) {
                  setState(() {
                    _selectedRole = value!;
                  });
                },
              ),
              const SizedBox(height: 16),

              // 部门
              TextFormField(
                controller: _departmentController,
                decoration: const InputDecoration(
                  labelText: '部门',
                  hintText: '请输入部门',
                  prefixIcon: Icon(Icons.business),
                ),
                validator: User.validateDepartment,
              ),
              const SizedBox(height: 16),

              // 职位
              TextFormField(
                controller: _positionController,
                decoration: const InputDecoration(
                  labelText: '职位',
                  hintText: '请输入职位',
                  prefixIcon: Icon(Icons.work),
                ),
                validator: User.validatePosition,
              ),
              const SizedBox(height: 32),

              // 操作按钮
              Row(
                children: [
                  Expanded(
                    child: ElevatedButton(
                      onPressed: _isLoading ? null : _saveUser,
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Color(AppConfig.primaryColor),
                        foregroundColor: Colors.white,
                        padding: const EdgeInsets.symmetric(vertical: 16),
                      ),
                      child: Text(_isEditMode ? '更新用户' : '创建用户'),
                    ),
                  ),
                  const SizedBox(width: 16),
                  Expanded(
                    child: OutlinedButton(
                      onPressed: _isLoading ? null : () => Navigator.of(context).pop(),
                      child: const Text('取消'),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
} 